package com.grow.greenhouse.filter;

import com.grow.greenhouse.common.ErrorCode;
import com.grow.greenhouse.exception.BusinessException;
import com.grow.greenhouse.once.UserContext;
import com.grow.greenhouse.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@WebFilter(urlPatterns = "/*",filterName = "loginCheckFilter")
@Slf4j
public class LoginCheckFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        List<String> allowList = new ArrayList<>(Arrays.asList("/api/user/login","/api/user/current","/api/user/register","/api/user/doc.html","/api/websocket/1","/api/websocket/2"));
        if(allowList.contains(request.getRequestURI()))
        {
            filterChain.doFilter(request,response);
        }
        else{
            log.info("拦截到请求：{}",request.getRequestURI());
            String token = request.getHeader("token");
            if(!JwtUtil.verifyToken(token)){
                throw new BusinessException(ErrorCode.NOT_LOGIN,"用户未登录");
            }
            filterChain.doFilter(request,response);
        }

    }
}
